#-*- coding:utf-8 -*-
from scrapyd_api import ScrapydAPI

from finance.models import spider_statues

__author__ = 'root'


from django.core.management.base import BaseCommand,CommandError

class Command(BaseCommand):
    def handle(self, *args, **options):
        spider_projects = 'sina_finance'
        spider_name = 'finance'
        scrapyd = ScrapydAPI(target='http://root:123456@192.168.1.46:6802')
        jod_id = scrapyd.schedule(spider_projects, spider_name)
        jod_state=None
        jod_list = scrapyd.list_jobs(spider_projects)
        for key, value in jod_list.items():
            jod_id_all = map(lambda x: x['id'], value)
            if jod_id in jod_id_all:
                if key == 'pending':
                    jod_state = 0
                elif key == 'running':
                    jod_state = 1
                elif key == 'finished':
                    jod_state = 2
                else:
                    jod_state = 3
                break
        if jod_state!=None:
            spider_statues.objects.create(peoject_name=spider_projects, spider_name=spider_name, spider_job_id=jod_id,staute=jod_state)